//
//  VoxperAppDelegate.m
//  Voxper
//
//  Created by Erphan on 2/2/11.
//  Copyright 2011 Smonte. All rights reserved.
//

#import "VoxperAppDelegate.h"


#import "RegisterStep1ViewController.h"
#import "EmptyViewController.h"
#import "CallInProgressViewController.h"
#import "ConfigurationViewController.h"

#import "SipManager.h"
#import "Constants.h"
#import "UIManager.h"
#import "Settings.h"

@implementation VoxperAppDelegate

@synthesize window;
@synthesize manager;
@synthesize uiManager;
@synthesize NavigationController = navController;

#pragma mark -
#pragma mark Application lifecycle

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {    
    
    // Override point for customization after application launch.
	m_bViewInitialized = NO;
	manager = [[SipManager alloc] init];
	uiManager = [[UIManager alloc] init];
	
	// Register for call state change notification from sip manager
	[[NSNotificationCenter defaultCenter] addObserver:uiManager selector:@selector(handleCallStateChangedNotification:) name:UICALLSTATE_CALLBACK object:nil];
	[[NSNotificationCenter defaultCenter] addObserver:uiManager selector:@selector(handleRegistrationStateChangedNotification:) name:UIREGISTRATION_CALLBACK object:nil];
	
	/****** PUSH NOTIFICATIONS *******/
	[[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound)];
	/****** END ******/
	
    // Add the view controller's view to the window and display.
    //[self.window addSubview:viewController.view];
    [self.window makeKeyAndVisible];
	
	[uiManager handleApplicationDidFinishedLaunchingWithOptions:launchOptions];
    	
    return YES;
}


- (void)applicationWillResignActive:(UIApplication *)application {
    /*
     Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
     Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
     */
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    /*
     Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
     If your application supports background execution, called instead of applicationWillTerminate: when the user quits.
     */
	[manager disconnect];
	exit(0);
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    /*
     Called as part of  transition from the background to the inactive state: here you can undo many of the changes made on entering the background.
     */
	//[manager connect:URL_SIPSERVER :[uiManager.settings getUserName] :[uiManager.settings getPassword]];
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    /*
     Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
     */
}


- (void)applicationWillTerminate:(UIApplication *)application {
    /*
     Called when the application is about to terminate.
     See also applicationDidEnterBackground:.
     */
}


#pragma mark -
#pragma mark Memory management

- (void)cleanUp {
	[[NSNotificationCenter defaultCenter] removeObserver:uiManager];
	[manager disconnect];
	[uiManager release];
	[manager release];
}

- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application {
    /*
     Free up as much memory as possible by purging cached data objects that can be recreated (or reloaded from disk) later.
     */
	NSLog(@"APP Delegate Memory Issue--------------------->>>>");
}


- (void)dealloc {
	[self cleanUp];
	[navController release];
    [window release];
    [super dealloc];
}

#pragma mark -
#pragma mark Push Notifications delegation

- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)devToken {
    //const void *devTokenBytes = [devToken bytes];
    //self.registered = YES;
	NSString *deviceToken = [[devToken description] stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];
	deviceToken = [deviceToken stringByReplacingOccurrencesOfString:@" " withString:@""];
	
	[uiManager.settings setDeviceToken:deviceToken];
    [uiManager sendDeviceToken];
    NSLog(@"Device Token: %@", deviceToken);
}

- (void)application:(UIApplication *)app didFailToRegisterForRemoteNotificationsWithError:(NSError *)err {
	NSLog(@"Error in registration. Error: %@", err);
	UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:@"Error" message:@"Push notification failed, you will not be able to receive offline calls." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] autorelease];
	[alert show];
}

// Called if notification is received while app is active
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
	NSLog(@"Received Notification (Active): %@", userInfo);
	
	NSString *strMessage = [NSString stringWithFormat:@"%@", [[userInfo objectForKey:@"aps"] objectForKey:@"alert"]];
	if ([strMessage rangeOfString:@"pin code"].length > 0) {
		
	} else {
		//[uiManager reloadConversations];
		return;
	}
	
	UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Voxper" message:strMessage delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
	[alert show];
	[alert release];
}

#pragma mark -
#pragma mark Public methods

- (void)initiateUI {
	if (m_bViewInitialized) {
		return;
	}
	m_bViewInitialized = YES;

    EmptyViewController *emptyViewController = [[EmptyViewController alloc] initWithNibName:@"EmptyViewController" bundle:[NSBundle mainBundle]];

    if ([self NavigationController]) {
        UINavigationController *_navController = [[UINavigationController alloc] initWithRootViewController:emptyViewController];
        [self.NavigationController presentModalViewController:_navController animated:YES];
    } else {
        [self setNavigationController:[[UINavigationController alloc] initWithRootViewController:emptyViewController]];
		[self.window addSubview:[self.NavigationController view]];
    }
    [emptyViewController release];
    
    //[manager connect:[uiManager.settings getServerName] :@"441481898007" :@"123"];
	[manager connect:[uiManager.settings getServerName] :[uiManager.settings getUserName] :[uiManager.settings getPassword]];
}

@end
